package com.hue.springbootneo4j.service.impl;

import com.hue.springbootneo4j.entity.Star;
import com.hue.springbootneo4j.entity.StarRelationShip;
import com.hue.springbootneo4j.repository.StarRepository;
import com.hue.springbootneo4j.service.StarService;
import com.hue.springbootneo4j.utils.TypeConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StarServiceImpl implements StarService {
    @Autowired
    private StarRepository starRepository;

    @Override
    public List<Star> all() {
        List<Map<String, Object>> all = starRepository.all();
        List<Star> starList = all.stream().map(map ->
                TypeConverter.parseObject(map, Star.class)
        ).collect(Collectors.toList());
        return starList;
    }

    @Override
    public Map<String, Object> byName(String name) {
        List<Map<String, Object>> maps = starRepository.byName(name);
        Map<String, Object> data = new HashMap<>();
        List<Star> nodes = new ArrayList<>();
        List<StarRelationShip> edges = new ArrayList<>();
        boolean first = false;
        for (Map<String, Object> map : maps) {
            Star start = new Star((Long) map.get("fromId"), (String) map.get("fromName"));
            Star end = new Star((Long) map.get("toId"), (String) map.get("toName"));
            StarRelationShip relationShip = new StarRelationShip();
            relationShip.setStart(start);
            relationShip.setEnd(end);
            relationShip.setRelation((String) map.get("relation"));
            if (!first) {
                nodes.add(start);
                first = true;
            }
            nodes.add(end);
            edges.add(relationShip);
        }
        data.put("nodes", nodes);
        data.put("edges", edges);
        return data;
    }
}
